    package com.ruoyi.web.controller.project;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.project.domain.entity.ProjectAttachment;
import com.ruoyi.project.domain.entity.ProjectCosting;
import com.ruoyi.project.domain.entity.ProjectParticipan;
import com.ruoyi.project.domain.query.ProjectFileQuery;
import com.ruoyi.project.domain.query.ProjectParticipanQuery;
import com.ruoyi.project.service.IProjectAttachmentService;
import com.ruoyi.project.service.IProjectCostingService;
import com.ruoyi.project.service.IProjectParticipanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

    @RestController
    @RequestMapping("/project/attachment")
    @Api(tags = "附件信息", description = "附件信息")
    public class ProjectFileController {


        @Resource
        private IProjectAttachmentService fileService;
        @Resource
        private IProjectCostingService costingService;

        @ApiOperation("分页")
        @GetMapping(value = "/list")
        public R getList(ProjectFileQuery query) {
            return R.ok(fileService.getList(query));
        }



        @ApiOperation("新增")
        @PostMapping(value = "/save")
        public R add(@RequestBody ProjectAttachment project) {
            String result = "";
            //如果是正式清单 需要保存正式清单的数据
            if (project.getAttachmentType().equals("5")){
                File file = null;
                try {
                    // 获取上传路径的基础路径
                    String baseUploadPath = RuoYiConfig.getUploadPath();
                    // 获取当前日期并格式化为 "yyyy\\MM\\dd" 格式
                    LocalDate currentDate = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    String datePath = currentDate.format(formatter);
                    // 拼接完整的文件路径
                    String filePath = baseUploadPath + "/" + datePath;
                    // 输出结果
                    System.out.println("完整的文件路径: " + filePath);
                    file = FileUploadUtils.getAbsoluteFile(filePath, project.getFileName());
                    FileInputStream fis = new FileInputStream(file);
                    ExcelUtil<ProjectCosting> util = new ExcelUtil<>(ProjectCosting.class);
                    List<ProjectCosting> list = util.importExcel(fis);
                    result = costingService.importCosting(list,project.getProjectNo(),project.getIsDelete(),"5");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

            if (project.getAttachmentType().equals("22")){
                File file = null;
                try {
                    // 获取上传路径的基础路径
                    String baseUploadPath = RuoYiConfig.getUploadPath();
                    // 获取当前日期并格式化为 "yyyy\\MM\\dd" 格式
                    LocalDate currentDate = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    String datePath = currentDate.format(formatter);
                    // 拼接完整的文件路径
                    String filePath = baseUploadPath + "/" + datePath;
                    // 输出结果
                    System.out.println("完整的文件路径: " + filePath);
                    file = FileUploadUtils.getAbsoluteFile(filePath, project.getFileName());
                    FileInputStream fis = new FileInputStream(file);
                    ExcelUtil<ProjectCosting> util = new ExcelUtil<>(ProjectCosting.class);
                    List<ProjectCosting> list = util.importExcel(fis);
                    result = costingService.importCosting(list,project.getProjectNo(),project.getIsDelete(),"22");
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }


            return R.ok(fileService.addInfo(project),result);
        }

        @ApiOperation("修改")
        @PutMapping (value = "/update")
        public R update(@RequestBody ProjectAttachment project) {
            //如果是正式清单 需要保存正式清单的数据
            if (project.getAttachmentType().equals("5")){
                File file = null;
                try {
                    // 获取上传路径的基础路径
                    String baseUploadPath = RuoYiConfig.getUploadPath();
                    // 获取当前日期并格式化为 "yyyy\\MM\\dd" 格式
                    LocalDate currentDate = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    String datePath = currentDate.format(formatter);
                    // 拼接完整的文件路径
                    String filePath = baseUploadPath + "/" + datePath;
                    // 输出结果
                    System.out.println("完整的文件路径: " + filePath);
                    file = FileUploadUtils.getAbsoluteFile(filePath, project.getFileName());
                    FileInputStream fis = new FileInputStream(file);
                    ExcelUtil<ProjectCosting> util = new ExcelUtil<>(ProjectCosting.class);
                    List<ProjectCosting> list = util.importExcel(fis);
                    costingService.importCosting(list,project.getProjectNo(),project.getIsDelete(),"5");
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage() + "请上传正确格式的正式清单excel文件");
                }
            }
            if (project.getAttachmentType().equals("22")){
                File file = null;
                try {
                    // 获取上传路径的基础路径
                    String baseUploadPath = RuoYiConfig.getUploadPath();
                    // 获取当前日期并格式化为 "yyyy\\MM\\dd" 格式
                    LocalDate currentDate = LocalDate.now();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                    String datePath = currentDate.format(formatter);
                    // 拼接完整的文件路径
                    String filePath = baseUploadPath + "/" + datePath;
                    // 输出结果
                    System.out.println("完整的文件路径: " + filePath);
                    file = FileUploadUtils.getAbsoluteFile(filePath, project.getFileName());
                    FileInputStream fis = new FileInputStream(file);
                    ExcelUtil<ProjectCosting> util = new ExcelUtil<>(ProjectCosting.class);
                    List<ProjectCosting> list = util.importExcel(fis);
                    costingService.importCosting(list,project.getProjectNo(),project.getIsDelete(),"22");
                } catch (IOException e) {
                    throw new RuntimeException(e.getMessage() + "请上传正确格式的正式清单excel文件");
                }
            }

            return R.ok(fileService.updateInfo(project));
        }


        @ApiOperation("删除")
        @DeleteMapping (value = "/{id}")
        public R delete(  @PathVariable("id") String id) {
            return R.ok(fileService.deleteInfo(id));
        }


        @ApiOperation("详情")
        @GetMapping(value = "/details")
        public R<ProjectAttachment> getDetails(@RequestParam String id) {
            return R.ok(fileService.getById(id));
        }

        @PostMapping("/importTemplate/{type}")
        public void importTemplate(@PathVariable("type") String type,HttpServletResponse response)
        {


//            String templatePath = "/zsqd.xlsx";
            String templatePath = "/" + type;
            String fileName = "正式清单";

            try {
                // 从 classpath 中加载资源文件
                ClassPathResource resource = new ClassPathResource(templatePath);
                if (!resource.exists()) {
                    throw new RuntimeException("模板文件不存在！");
                }
                // 获取文件输入流
                InputStream inputStream = resource.getInputStream();
                // 设置响应头
                response.setContentType("application/vnd.ms-excel");
                response.setCharacterEncoding("utf-8");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                        "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
                // 将文件内容写入响应输出流
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    response.getOutputStream().write(buffer, 0, bytesRead);
                }
                // 刷新输出流
                response.getOutputStream().flush();
                response.getOutputStream().close();
                inputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("下载模板文件失败：" + e.getMessage());
            }
        }

    }
